package assdraw2.canvas.abstraction;

import java.awt.Color;
import java.awt.Rectangle;
import java.util.Vector;
import assdraw2.canvas.presentation.Visitor;
import assdraw2.canvas.abstraction.Shape;


public class ShapeGroup extends Shape{

	private Vector<Shape> components;
	
	public ShapeGroup(){
		components = new Vector<Shape>();
	}
	
	public ShapeGroup(Vector<Shape> components){
		this.components = new Vector<Shape>();
		this.components.addAll(components);
		
		this.setX((int)getBoundary().getX());
		this.setY((int)getBoundary().getY());
	}

	@Override
	public void setColor(Color c){
		for(Shape s : components){
			s.setColor(c);
		}
	}
	
	@Override
	public Vector<Shape> ungroup(){
		return components;
	}

	@Override
	public void scale(double fx, double fy) {
		for(Shape s : components){
			
			s.move(getX()+ (s.getX()-getX())*fx, getY()+ (s.getY()-getY())*fy);
			s.scale(fx, fy);
		}
	}
	
	@Override
	public boolean contains(double x2, double y2) {
		for(Shape s : components){
			if(s.contains(x2, y2))
				return true;
		}
		return false;
	}
	
	@Override
	public void move(double x, double y){
		
		for(Shape s : components){
			s.move(s.getX() + x-this.getX(), s.getY() + y-this.getY());
		}
		this.setX(x);
		this.setY(y);
	}
	
	public void addComponent(Shape s){
		components.add(components.size(), s);
	}
	
	public void setComponents(Vector<Shape> components) {
		this.components = components;
	}

	public Vector<Shape> getComponents() {
		return components;
	}


	@Override
	public void accept(Visitor v) {
		v.visit(this);
	}


	@Override
	public Rectangle getBoundary() {
		int[] xmin = new int[components.size()];
		int[] ymin = new int[components.size()];
		int[] xmax = new int[components.size()];
		int[] ymax = new int[components.size()];
		
		for(int i=0; i<components.size(); i++){
			xmin[i] = components.get(i).getBoundary().x;
			ymin[i] = components.get(i).getBoundary().y;
			xmax[i] = components.get(i).getBoundary().x + components.get(i).getBoundary().width;
			ymax[i] = components.get(i).getBoundary().y + components.get(i).getBoundary().height;
		}
		int rx = min(xmin);
		int ry = min(ymin);
		int w = max(xmax) - rx;
		int h = max(ymax) - ry;
		
		return new Rectangle(rx, ry, w, h);
	}

	
	public static int min(int[] arr){
		int r = Integer.MAX_VALUE;
		for(int i=0; i<arr.length; i++){
			if(arr[i]<r)
				r=arr[i];
		}
		return r;
	}
	
	public static int max(int[] arr){
		int r = Integer.MIN_VALUE;
		for(int i=0; i<arr.length; i++){
			if(arr[i]>r)
				r=arr[i];
		}
		return r;
	}
}
